import RootStateTypes from "@/store/interface";
import AppInterface from "./interface"
import { Module } from "vuex";
import { goodsTypeList, goodsSpecList } from "@/api/data";
import { GoodsType, GoodsSpec } from "@/utils/interface";

const appModule: Module<AppInterface, RootStateTypes> = {
  namespaced: true,
  state: {
    goodsType: [], // 商品分类
    goodsSpec: [], // 商品规格
  },
  mutations: {
    set_goodsType(state: any, newData: Array<GoodsType>) {
      state.goodsType = newData;
    },
    set_goodsSpec(state: any, newData: Array<GoodsSpec>) {
      state.goodsSpec = newData;
    }
  },
  actions: {

    // 获取商品类型
    getGoodsType({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.goodsType.length == 0) {
          goodsTypeList().then(res => {
            commit('set_goodsType', res)
            resolve(res)
          }).catch(function (error) {
            reject(error)
          })
        } else {
          resolve(state.goodsType)
        }
      })
    },

    // 更新商品分类数据
    updateType({ commit }) {
      goodsTypeList().then(res => {
        commit('set_goodsType', res)
      })
    },

    // 获取商品规格
    getGoodsSpec({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.goodsSpec.length == 0) {
          goodsSpecList().then(res => {
            commit('set_goodsSpec', res)
            resolve(res)
          }).catch(function (error) {
            reject(error)
          })
        } else {
          resolve(state.goodsSpec)
        }
      })
    },

    // 更新商品规格
    updateSpec({ commit }) {
      goodsSpecList().then(res => {
        commit('set_goodsSpec', res)
      })
    },


  }
};
export default appModule;